package secondriver.heathfood;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import secondriver.heathfood.bean.FoodDetail;
import secondriver.heathfood.common.BackgroundTaskExecutor;
import secondriver.heathfood.common.BackgroundTasks;
import secondriver.heathfood.exception.SysUncaughtExceptionHandler;
import secondriver.heathfood.util.LogUtil;
import secondriver.heathfood.util.unused.SimpleSQLiteCache;
import secondriver.heathfood.util.unused.SimpleSQLiteHelper;

import java.lang.ref.SoftReference;
import java.util.Stack;

/**
 * Author : secondriver
 * Date :  2015/10/21
 */
public class HeathFoodApplication extends Application {

    public static final String META_KEY_GET_APP_VERSION_URL = "getAppVersionUrl";
    public static final String META_KEY_LOG_LEVEL = "logLevel";
    public static final String META_KEY_ENABLE_EXCEPTION_HANDLER = "enableExceptionHandler";

    public static final String DATABASE_NAME = "heath_food.sqlite";

    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();

        try {
            ApplicationInfo applicationInfo = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
            if (null != applicationInfo) {
                Bundle meta = applicationInfo.metaData;

                //初始化日志
                String logLevel = meta.getString(META_KEY_LOG_LEVEL, LogUtil.Level.NOTHING.name());
                LogUtil.Level level = LogUtil.Level.valueOf(logLevel.toUpperCase());
                LogUtil.initLogLevel(level);

                //初始化未捕获异常
                boolean enableExceptionHandler = meta.getBoolean(META_KEY_ENABLE_EXCEPTION_HANDLER, true);
                if (enableExceptionHandler) {
                    SysUncaughtExceptionHandler.initSysUncaughtExceptionHandler(context);
                }

                //获取appversionUrl
                if (isNetworkAvailable()) {
                    String appVersionUrl = meta.getString(META_KEY_GET_APP_VERSION_URL);
                    Bundle bundle = new Bundle();
                    bundle.putString(META_KEY_GET_APP_VERSION_URL, appVersionUrl);
                    BackgroundTaskExecutor.doTask(bundle, null, new
                            BackgroundTasks.PullAppVersionInfoTask(context));
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Context getContext() {
        return context;
    }

    public static int getVersionCode() {
        try {
            int versionCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
            return versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static String getVersionName() {
        try {
            String versionName = context.getPackageManager().getPackageInfo(context.getPackageName
                    (), 0).versionName;
            return versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager =
                (ConnectivityManager) getContext().getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo();
        for (NetworkInfo networkInfo : networkInfos) {
            if (networkInfo.getState() == NetworkInfo.State.CONNECTED) {
                return true;
            }
        }
        return false;
    }


    public static SimpleSQLiteHelper getSQLiteHelper() {
        return SimpleSQLiteHelper.Creator(getContext())
                .name(DATABASE_NAME)
                .cursorFactory(null)
                .version(2)
                .databaseErrorHandler(null)
                .addCreateScript(FoodDetail.MetaInfo.getInitScript())
                .addCreateScript(SimpleSQLiteCache.MetaInfo.getInitScripts())
                .addUpgradeScript("ALTER TABLE " + FoodDetail.MetaInfo.TABLE_NAME + " ADD COLUMN f_rcount VARCHAR;")
                .create();
    }

    public static SimpleSQLiteCache getSQLiteCache() {
        return SimpleSQLiteCache.getInstance(getSQLiteHelper());
    }

    //    public static class ActivityCollector {
//
//        private static final Stack<Activity> mActivities = new Stack<Activity>();
//
//        public static void addActivity(Activity activity) {
//            mActivities.push(activity);
//        }
//
//        public static void removeActivity(Activity activity) {
//            mActivities.remove(activity);
//        }
//
//        public static void finishAllActivity() {
//            while (!mActivities.empty()) {
//                Activity activity = mActivities.pop();
//                if (null != activity && !activity.isFinishing()) {
//                    activity.finish();
//                }
//            }
//            android.os.Process.killProcess(android.os.Process.myPid());
//        }
//    }
    public static class ActivityCollector {

        private static final Stack<SoftReference<Activity>> mActivities = new Stack<>();


        public static void addActivity(Activity activity) {
            SoftReference ref = new SoftReference(activity);
            mActivities.push(ref);
        }

        public static void removeActivity(Activity activity) {
            mActivities.remove(activity);
        }

        public static void finishAllActivity() {
            while (!mActivities.empty()) {
                SoftReference<Activity> ref = mActivities.pop();
                Activity activity = ref.get();
                if (null != activity && !activity.isFinishing()) {
                    activity.finish();
                }
            }
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }
}
